﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Collections.Generic;

namespace TileBoard.WebParts.TileBoard
{
    [ToolboxItemAttribute(false)]
    public class TileBoard :  Microsoft.SharePoint.WebPartPages.WebPart
    {
        string[] colors = {"Black","Blue","Brown","Green","Grey","Maroon","Navy","Orange","Pink","Purple","Red","Silver","Olive"};
        Guid _listId, _listWeb;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        public string _fieldFrontText = "", _fieldHyperlink = "", _fieldPicture = "", _fieldBackText = "", _fieldColor = "";
        private List<string> _fieldNames = new List<string>();

        string _js = @"<script src=""/_layouts/Tileboard/jquery-1.7.1.min.js"" type=""text/javascript""></script><script src=""/_layouts/Tileboard/MetroJs.js"" type=""text/javascript""></script>
                        <script type=""text/javascript"">
                            $(document).ready(function () {
                                $("".live-tile,.flip-list"").liveTile(
                                    {
                                        playOnHover: true
                                    }
                                );
                            });
                        </script>";

        string _css = @"<link href=""/_layouts/Tileboard/MetroJs.css"" rel=""stylesheet"" type=""text/css"" />";

        [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
        public Guid ListId
        {
            get { return this._listId; }
            set { this._listId = value; }
        }

        [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
        public List<string> FieldNames
        {
            get { return this._fieldNames; }
            set { this._fieldNames = value; }
        }

        [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
        public Guid ListWebId
        {
            get { return this._listWeb; }
            set { this._listWeb = value; }
        }

        [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
        public string FrontText
        {
            get { return this._fieldFrontText; }
            set { this._fieldFrontText = value; }
        }

        [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
        public string Hyperlink
        {
            get { return this._fieldHyperlink; }
            set { this._fieldHyperlink = value; }
        }

        [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
        public string Picture
        {
            get { return this._fieldPicture; }
            set { this._fieldPicture = value; }
        }

        [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
        public string BackText
        {
            get { return this._fieldBackText; }
            set { this._fieldBackText = value; }
        }

        [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
        public string Color
        {
            get { return this._fieldColor; }
            set { this._fieldColor = value; }
        }

        protected override void CreateChildControls()
        {
        }

        public override ToolPart[] GetToolParts()
        {
            ToolPart[] allToolsParts = new ToolPart[3];
            try
            {
                WebPartToolPart standardToolParts = new WebPartToolPart();
                CustomPropertyToolPart customToolParts = new CustomPropertyToolPart();

                allToolsParts[0] = standardToolParts;
                allToolsParts[1] = customToolParts;
                allToolsParts[2] = new Toolpart();
            }
            catch 
            {
            }

            return allToolsParts;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            sb.AppendLine(_js);
            sb.AppendLine(_css);
            try
            {
                Guid emptyGuid = new Guid("00000000-0000-0000-0000-000000000000");
                if (this._listId != emptyGuid)
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                        {
                            using (SPWeb web = site.OpenWeb(this.ListWebId))
                            {
                                SPList list = web.Lists[this._listId];
                                // Nik20130523 - Randomize a number between 0 and 1 to determine what animation type to display between slide(0) and flip (1);
                                System.Random rnd = new Random(System.DateTime.Now.Millisecond);
                                Random rndColor = new Random(DateTime.Now.Millisecond);
                                if (list != null)
                                {
                                    int animationIndex = rnd.Next(0, 3);
                                    
                                    foreach (SPListItem item in list.Items)
                                    {
                                        string color = "", hyperlink = "", backText = "", frontText = "", picture = "";
                                        animationIndex = rnd.Next(0, 3);
                                        //try
                                        //{
                                            int delay = rnd.Next(5000, 10000);
                                            if (animationIndex == 0)
                                                sb.AppendLine(@"<div class=""live-tile"" data-delay=""" + delay.ToString() + @""">");
                                            else if(animationIndex == 1)
                                                sb.AppendLine(@"<div class=""live-tile"" data-mode=""flip"" data-delay=""" + delay.ToString() + @""">");
                                            else
                                                sb.AppendLine(@"<div class=""live-tile"" data-mode=""carousel"" data-direction=""horizontal"" data-delay=""" + delay.ToString() + @""">");

                                            if (item[Hyperlink] != null)
                                            {
                                                hyperlink = item[Hyperlink].ToString();
                                                if (!hyperlink.StartsWith("/") || !hyperlink.StartsWith("http:"))
                                                    hyperlink = SPContext.Current.Web.Url + "/" + hyperlink;
                                            }

                                            if (Color == "[Random]")
                                            {                                                
                                                int colorIndex = rndColor.Next(0, colors.Length);
                                                color = colors[colorIndex];
                                            }
                                            else if (item[Color] != null)
                                                color = item[Color].ToString();   
                                            
                                            if (BackText != "[None]" && item[BackText] != null)
                                                backText = item[BackText].ToString();

                                            if (item[FrontText] != null)
                                                frontText = item[FrontText].ToString();

                                            if (item[Picture] != null)
                                            {
                                                picture = item[Picture].ToString();
                                                if (!picture.StartsWith("/") && !picture.StartsWith("http:"))
                                                    picture = SPContext.Current.Web.Url + "/" + picture;
                                            }

                                            sb.AppendLine(@"<div style=""box-shadow: 10px 10px 5px #888888;background-color:" + color + @";font-weight:bold;font-size:130%;""><a href=""" + hyperlink + @""" style=""width:130px;height:130px;display:block;color:white;text-decoration:none;padding:10px;"">" + frontText + "</a></div>");
                                            sb.AppendLine(@"<div style=""box-shadow: 10px 10px 5px #888888;background-color:" + color + @";font-weight:bold;font-size:130%;""><a href=""" + hyperlink + @""" style=""width:150px;height:150px;display:block;color:white;text-decoration:none;"">");
                                            if (item[Picture] != null)
                                            {
                                                sb.AppendLine("<span style=\"position:absolute;left:10px;top:10px;background: rgba(0, 0, 0, 0.7);color:white;font: bold 120%/120% Helvetica, Sans-Serif; letter-spacing: -1px; background: rgb(0, 0, 0);\">" + backText + "</span><img src=\"" + picture.Split(',')[0] + "\" width=\"150px;\" height=\"150px;\" alt=\"" + Title + "\" />");
                                            }
                                            else
                                            {
                                                sb.AppendLine(backText);
                                            }
                                            sb.AppendLine("</a></div>");
                                            sb.AppendLine("</div>");
                                        //}
                                        //catch { }
                                    }
                                }
                            }
                        }
                    });
                }
            }
            catch { }
            
            writer.Write(sb.ToString());
        }
    }
}
